package com.starblink.android.basic.data

import android.content.Context
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import com.starblink.android.basic.config.GuangConfig
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.event.TrackEvent
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.basic.storage.SkStorage
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

object GaidReportManager {

    /**
     * 上报广告id
     */
    fun reportDeviceId(context: Context) {
        if (SkStorage.getString(GuangConfig.REPORT_GA_ID, "")?.isEmpty() == true) {
            CoroutineScope(Dispatchers.IO).launch {
                try {
                    val adid: String? =
                        AdvertisingIdClient.getAdvertisingIdInfo(context).id
//                    LogUtils.e("GuangApp", "adid:$adid")
                    if (adid?.isNotEmpty() == true && adid?.contains("00000000-0000-0000-0000-000000000000") == false) {
                        SpmTrackHandler.addSingleTrackData(
                            SkAntEntity(
                                event = TrackEvent.appLifeCycle.value,
                                spmCnt = GTrackerAssistUtils.fetchElementValue(
                                    0,
                                    SpmElementDef.AppUpGAID
                                ),
                                params = mapOf("adId" to adid)
                            )
                        )
                        SkStorage.put(GuangConfig.REPORT_GA_ID, adid)
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
    }
}